package com.marketsim.simulator;

import com.marketsim.analysis.BigDecimalConverter;
import com.marketsim.common.bean.HistoryPriceBean;
import com.marketsim.utils.BigDecimalUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Alex on 30.03.2014.
 */
public class PricesHistoricalData {

    private List<String> tickersHeader;
    private List<List<HistoryPriceBean>> pricesHistory;

    public PricesHistoricalData(List<List<HistoryPriceBean>> pricesHistory, List<String> tickersHeader) {
        this.pricesHistory = pricesHistory;
        this.tickersHeader = tickersHeader;
    }

    private PricesHistoricalData(){};

    public BigDecimal getPrice(String ticker, Date date) {
        int tickerIndex = tickersHeader.indexOf(ticker);
        for (HistoryPriceBean priceBean : pricesHistory.get(tickerIndex)) {
            if (priceBean.getDate().equals(date)) {
                return priceBean.getAdjClose();
            }
        }
        return null;
    }

    public List<List<BigDecimal>> getReturns() {
        List<List<BigDecimal>> result = new ArrayList<>();

        for(List<HistoryPriceBean> priceList : pricesHistory) {
            //TODO parametrize field for converter
            BigDecimalConverter<HistoryPriceBean> converter = (from) -> from.getAdjClose();
            List<BigDecimal> inputList = new ArrayList<>(priceList.size());
            priceList.stream().map(converter::convert).sorted().forEach((val) -> inputList.add(val));

            List<BigDecimal> resultInBigDecimal = new ArrayList<>(priceList.size()-1);
            for(int i=1; i<priceList.size(); i++) {
                resultInBigDecimal.add(inputList.get(i).divide(inputList.get(i - 1), BigDecimalUtils.SCALE, RoundingMode.HALF_UP).subtract(BigDecimal.ONE));
            }
            result.add(resultInBigDecimal);
        }

        return result;
    }
}
